package com.wanmait.employment.aop;

import com.wanmait.employment.entity.Admin;
import com.wanmait.employment.entity.Log;
import com.wanmait.employment.service.LogService;
import com.wanmait.employment.util.IPUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private LogService logService;

    //切入点表达式 切入加了LogInfo注解的所有方法
    @Pointcut("@annotation(com.wanmait.employment.aop.LogInfo)")
    public void pointcuntExpression(){}

    @AfterReturning(value = "pointcuntExpression()",returning = "returnValue")
    public void saveLog(JoinPoint point,Object returnValue){
        //获得request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        Admin admin = (Admin) request.getAttribute("admin");
        if(admin!=null){
            MethodSignature signature = (MethodSignature)point.getSignature();
            Method method = signature.getMethod();
            LogInfo logInfo = method.getAnnotation(LogInfo.class);
            Log log = new Log();
            log.setAdminId(admin.getId());
            log.setIp(IPUtils.getClientIpAddr(request));

            StringBuilder builder = new StringBuilder(logInfo.value());
            builder.append(";类：").append(point.getTarget().getClass().getName()).append(";");
            builder.append("方法：").append(point.getSignature().getName()).append(";");
            builder.append("参数：").append(Arrays.asList(point.getArgs())).append(";");
            if(returnValue!=null){
                builder.append("返回类型：").append(returnValue.getClass().getName()).append(";");
                builder.append("返回值：").append(returnValue).append(";");
            }

            log.setInfo(builder.toString());
            logService.save(log);
        }
    }
}













